//
//  dygContactViewController.m
//  myRecordingPhone
//
//  Created by 于国洋 on 2018/6/18.
//  Copyright © 2018年 于国洋. All rights reserved.
//

#import "ContactController.h"
#import "ContactCell.h"
#import <LJPerson.h>
#import <LJContactManager.h>

@interface ContactController ()

@property (nonatomic, copy) NSArray *keys;

@end

@implementation ContactController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadContactData];
}

-(void)loadContactData {
    [[LJContactManager sharedInstance] accessSectionContactsComplection:^(BOOL succeed, NSArray<LJSectionPerson *> *contacts, NSArray<NSString *> *keys) {
        [self.dataSource addObjectsFromArray:contacts];
        self.keys = keys;
        [self.tableView reloadData];
    }];
    
    [self.tableView cellWithNib:ContactCell.class];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ContactCell * cell = [tableView dequeueWithClass:ContactCell.class];
    LJSectionPerson *sectionModel = self.dataSource[indexPath.section];
    LJPerson *personModel = sectionModel.persons[indexPath.row];
    cell.model = personModel;
    return cell;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.keys;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.keys[section];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    LJSectionPerson *sectionModel = self.dataSource[section];
    return sectionModel.persons.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LJSectionPerson * sectionModel = self.dataSource[indexPath.section];
    LJPerson * personModel = sectionModel.persons[indexPath.row];
    MJWeakSelf
    [PhoneCallManager showPhoneNumber:personModel selectPhoneNumber:^(NSString * _Nonnull number) {
        if (weakSelf.selectNumberHandle) {
            weakSelf.selectNumberHandle(number);
            [weakSelf.navigationController popViewControllerAnimated:true];
        }else{
            [PhoneCallManager callPhoneNumber:number];
        }
    }];
}

@end
